package pdf2imag

import (
	"fmt"
	"os"
	"strings"

	"gitee.com/wuzheng0709/backend-gopkg/infrastructure/config"
	openClient "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	"github.com/alibabacloud-go/docmind-api-20220711/client"
	"github.com/alibabacloud-go/tea-utils/v2/service"
)

func Submit1(file_path string) (string, error) {
	ak := config.C.Oss.AccessKeyId
	sk := config.C.Oss.AccessKeySecret
	// 访问的域名，支持ipv4和ipv6两种方式，ipv6请使用docmind-api-dualstack.cn-hangzhou.aliyuncs.com
	var endpoint string = "docmind-api.cn-hangzhou.aliyuncs.com"
	config := openClient.Config{AccessKeyId: &ak, AccessKeySecret: &sk, Endpoint: &endpoint}
	// 初始化client
	cli, err := client.NewClient(&config)
	if err != nil {
		panic(err)
		return "", err
	}
	// 上传本地文档调用接口
	//filename := "C:/Users/admin/Desktop/file1.pdf"
	filename := file_path
	f, err := os.Open(filename)
	if err != nil {
		panic(err)
		return "", err
	}
	// 初始化接口request
	request := client.SubmitConvertPdfToImageJobAdvanceRequest{
		FileName:      &filename,
		FileUrlObject: f,
	}
	// 创建RuntimeObject实例并设置运行参数
	options := service.RuntimeOptions{}
	response, err := cli.SubmitConvertPdfToImageJobAdvance(&request, &options)
	if err != nil {
		panic(err)
		return "", err
	}
	// 打印结果
	fmt.Println(response.Body.String())
	return *response.Body.Data.Id, err
}

func Submit2(id string) (string, error) {
	ak := config.C.Oss.AccessKeyId
	sk := config.C.Oss.AccessKeySecret
	// 访问的域名，支持ipv4和ipv6两种方式，ipv6请使用docmind-api-dualstack.cn-hangzhou.aliyuncs.com
	var endpoint string = "docmind-api.cn-hangzhou.aliyuncs.com"
	config := openClient.Config{AccessKeyId: &ak, AccessKeySecret: &sk, Endpoint: &endpoint}
	// 初始化client
	cli, err := client.NewClient(&config)
	if err != nil {
		panic(err)
		return "", err
	}
	//id := "docmind-20230206-3a9091de"
	//id := id
	// 调用查询接口
	request := client.GetDocumentConvertResultRequest{Id: &id}
	response, err := cli.GetDocumentConvertResult(&request)
	if err != nil {
		panic(err)
		return "", err
	}
	// 打印查询结果
	fmt.Println(response.Body)
	//注意，使用go语言sdk会将返回结果中Url中的特殊字符&做Unicode转码，转码成\u0026，需要调用者手动将\u0026进行Unicode转码回&，才可以正常下载URL
	//go语言sdk的Url返回示例如下http://docmind-api-cn-hangzhou.oss-cn-hangzhou.aliyuncs.com/convert/docmind-20220927-87ad**/example.pdf?Expires=XX\u0026OSSAccessKeyId=YY\u0026Signature=ZZ

	if len(response.Body.Data) > 0 {
		str := *response.Body.Data[0].Url
		str = strings.Replace(str, "\\u0026", "&", -1)
		return str, err
	} else {
		return "", err
	}

}
